﻿Ext.override(NExt.UI.Edit.Base.EditPresenterBase, {

    templateInitializeEvents: function() {
        NExt.UI.Edit.Base.EditPresenterBase.superclass.templateInitializeEvents.call(this);
        this.addEvents('beforeSave', 'afterSave');
        this.addEvents('beforeCancel', 'afterCancel');
    },
    
    fireSave: function() {
        this.fireEvent('beforeSave');
        this.templateSave();
        this.fireEvent('afterSave');
    },

    templateSave: Ext.emptyFn,

    fireCancel: function() {
        this.fireEvent('beforeCancel');
        this.templateCancel();
        this.fireEvent('afterCancel');
    },

    templateCancel: function(){
        this.fireClose();
    },
    
    currentModel: undefined,

    getCurrentModel: function() {
        var model = this.formPanel.getModel();
        Ext.apply(this.currentModel, model);
        return this.currentModel;
    },

    setCurrentModel: function(model) {
        this.formPanel.setModel(model);
        this.currentModel = model;
    },

    initializeRights: function() {
        var editingType = this.getEditingType();
        var isInserting = (editingType & NExt.edit.presenter.EditingType.Insert) == NExt.edit.presenter.EditingType.Insert;
        var isEditing = (editingType & NExt.edit.presenter.EditingType.Edit) == NExt.edit.presenter.EditingType.Edit;

        var canNew = this.rightSetter.isEnabled(NExt.UI.Base.Right.Action.New);
        canNew = Ext.isDefined(canNew) ? canNew : false;

        var canEdit = this.rightSetter.isEnabled(NExt.UI.Base.Right.Action.Edit);
        canEdit = Ext.isDefined(canEdit) ? canEdit : false;

        var canSave = (canNew && isInserting) || (canEdit && isEditing);
        var canCancel = (canNew && isInserting) || (canEdit && isEditing);
        var canExit = true;

        this.tbbCancel.setDisabled(!canCancel);
        this.tbbExit.setDisabled(!canExit);
        this.tbbSave.setDisabled(!canSave);
    },

    showPresenter: function(model, editingType) {
        NExt.UI.Edit.Base.EditPresenterBase.superclass.showPresenter.call(this, model, editingType);
        this.initializeRightSetter();
    },

    initializeRightSetter: function() {
        if (this.rightSetter instanceof NExt.UI.Base.Right.CompositeRightSetter) {
            for (i = 0; i < this.rightSetter.rightSetterList.length; i++) {
                var innerRightSetter = this.rightSetter.rightSetterList[i];
                if (innerRightSetter instanceof NExt.UI.Base.Right.BindingSourceRightSetter) {
                    innerRightSetter.setBindingSource(this);
                }
            }
        }

        if (this.rightSetter instanceof NExt.UI.Base.Right.BindingSourceRightSetter) {
            this.rightSetter.setBindingSource(this);
        }

        this.rightSetter.on('needRefresh', this.initializeRights, this);
        this.initializeRights();
    }
});
